# -*- coding: utf-8 -*-

"""
Module implementing LabWindow.
"""
import sys,codecs,HandleFile,os,xml.dom.minidom
import visa
from SerialCom import RSerial
from PyQt5.QtCore import pyqtSlot,QIODevice
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMainWindow,QFileDialog,QMessageBox
from Ui_LABTOOL import Ui_MainWindow
from PyQt5.QtSerialPort import QSerialPort

global Dict

class LabWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget
        @type QWidget
        """
        super(LabWindow, self).__init__(parent)
        self.setupUi(self)
        self.comboBox_SerialCom.addItems(RSerial.getAvailablePortName(RSerial))
        L = HandleFile.getFileName(".\\cfg\\")
        self.comboBox_SelectPro.addItems(L)
        self.parserAT(self.comboBox_SelectPro.currentText())



    def readData(self):
        Data = self.ser.readAll()
        codec = codecs.decode(Data)
        self.textEdit.insertPlainText(codec)
        self.textEdit.ensureCursorVisible()
        size = codec.find("GPGSV")
        if(size >= 0):
            snr = codec[size:size+50]
            print(snr)


        
    def writeData(self,data):
        self.ser.write(data)


    def parserAT(self,proName):
        self.comboBox_ATSelect.clear()
        self.comboBox_ATSelect.addItem("--:--")
        dom = xml.dom.minidom.parse("cfg\\"+proName+".xml")
        root = dom.documentElement
        tagNames = root.getElementsByTagName("setp")
        for tagName in tagNames:
            if tagName.getElementsByTagName("cmd"):
                self.comboBox_ATSelect.addItem(tagName.getAttribute("name")+":"+tagName.getElementsByTagName("cmd")[0].childNodes[0].data)
            else:
                continue



    @pyqtSlot()
    def on_pushButton_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        self.comboBox_SerialCom.clear()
        self.comboBox_SerialCom.addItems(RSerial.getAvailablePortName(RSerial))
        
    @pyqtSlot()
    def on_pushButton_OpenCom_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        com = self.comboBox_SerialCom.currentText()
        self.ser = QSerialPort(com)
        self.ser.setBaudRate(int(self.comboBox_bund.currentText()))
        self.ser.open(QIODevice.ReadWrite)
        self.ser.readyRead.connect(self.readData)

    
    @pyqtSlot()
    def on_pushButton_CloseCom_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        try:
            self.ser.close()
        except:
            pass


    
    @pyqtSlot()
    def on_pushButton_SendAT_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        data = self.lineEdit_AT.text()
        data1 = codecs.encode(data+"\r\n")
        self.writeData(data1)
    
    @pyqtSlot()
    def on_pushButton_Clear_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        self.textEdit.clear()
    
    @pyqtSlot()
    def on_pushButton_Save_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        saveLog = QFileDialog.getSaveFileName(self,"saveLog",".","text(*.txt)")
        url = saveLog[0]
        fileName = os.path.basename(url)
        fileHandle = open(fileName,'a+')
        fileHandle.write(self.textEdit.toPlainText())
        fileHandle.close()

    @pyqtSlot(str)
    def on_comboBox_SelectPro_activated(self, p0):
        """
        Slot documentation goes here.
        @param index DESCRIPTION
        @type int
        """
        # TODO: not implemented yet
        self.parserAT(self.comboBox_SelectPro.currentText())
        
    @pyqtSlot(str)
    def on_comboBox_ATSelect_activated(self, p0):
        """
        Slot documentation goes here.
        
        @param p0 DESCRIPTION
        @type str
        """
        # TODO: not implemented yet
        try:
            atCommand = self.comboBox_ATSelect.currentText().split(":")[1]
            data = codecs.encode(atCommand+"\r\n")
            self.writeData(data)

        except:
            QMessageBox.question(self, '提示：', '检查串口是否打开！',
                                             QMessageBox.Yes, QMessageBox.Yes)

    @pyqtSlot()
    def on_pushButton_gpsTest_clicked(self):
        try:
            pass
        except:
            pass

    @pyqtSlot()
    def on_pushButton_InitPSU_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        rm = visa.ResourceManager()
        inst = rm.open_resource(self.lineEdit_gpibAdd.text())
        inst.write("VOLT 0")
        inst.write("OUTP 0")
    
    @pyqtSlot()
    def on_pushButton_setVoltage_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet

    
    @pyqtSlot()
    def on_pushButton_outPut_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet




if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = LabWindow()
    mainWindow.show()
    sys.exit(app.exec_())
    
